<script setup>
import {reactive, watch} from "vue";
import {MdPreview} from 'md-editor-v3';
// preview.css相比style.css少了编辑器那部分样式
import 'md-editor-v3/lib/preview.css';

const props = defineProps({
  data: String,
  url: String
})


const historyMessage = reactive([])


watch(() => props.data, async (newData) => {
  if (newData) {
    const newMessage = {
      id: historyMessage.length,
      role: "user",
      content: newData
    }
    historyMessage.push(newMessage)

    let historyMessageList = []

    for (let i = 0; i < historyMessage.length; i++) {
      historyMessageList.push(historyMessage[i].content)
    }

    // if (historyMessageList.length > 10 ) {
    //   historyMessageList = historyMessageList.slice(historyMessageList.length-11, historyMessageList.length)
    // }

    const bodyData = {
      history: historyMessageList,
      query: historyMessageList[historyMessageList.length - 1]
    }

    console.log(bodyData)

    const response = await fetch(props.url, {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(bodyData)
    })


    const reader = response.body.getReader()
    const gptResponse = {
      id: historyMessage.length, role: 'gpt', content: ""
    }

    historyMessage.push(gptResponse)
    const output = ({done, value}) => {
      console.log(value)
      if (done) {
        console.log('结束')
        return
      } else {
        const text = new TextDecoder().decode(value)
        historyMessage[historyMessage.length - 1].content += text
      }
      reader.read().then(output)
    }
    reader.read().then(output)

  }
})

</script>

<template>
  <div class="message-box">
    <div class="message-box" v-for="message in historyMessage" :key="message.id">
      <div v-if="message.role==='user'">
        <div class="message user">{{ message.content }}</div>
      </div>
      <div v-else>
        <MdPreview class="message gpt" :editorId="'aaaa'" :modelValue="message.content" style="width: auto; max-width: 600px"/>
      </div>
    </div>

  </div>
</template>

<style scoped>


.message-box .user {
  height: 30px;
  //text-align: center;
  line-height: 30px;
  //border: 1px solid black;
  margin-top: 5px;
  display: inline-block;
  float: right;
  clear: both;
  margin-left: 10px;
  padding: 0 15px;
  border-radius: 45px;
  background-color: rgba(204, 182, 182, 0.2);
  margin-right: 10px;
  color: black
}

.message-box .gpt {
  height: 30px;
  max-width: 610px;
  //text-align: center;
  line-height: 30px;
  //border: 1px solid black;
  margin-top: 5px;
  display: inline-block;
  float: left;
  clear: both;
  margin-right: 10px;
  padding: 0 15px;
  border-radius: 10px;
  //background-color: black;
  color: white;
  margin-left: 10px;
}

.message-box .user,
.message-box .gpt {
  height: auto; /* 改为自动高度 */
  white-space: normal; /* 允许自动换行 */
  overflow-wrap: break-word; /* 当单词长度超过容器宽度时自动换行 */
  /* 其他样式保持不变 */
}
</style>